package com.meichis.mcsappframework.utils;

import android.app.Activity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Stack;

/**
 * Created by chenhaifei on 2016/3/22.
 */
public class ActivityUtils {
    private static ActivityUtils instance;
    // activity堆栈，用于存放所有开启状态的activity,采用WeakReference,避免对GC产生影响
    private Stack<WeakReference<Activity>> activityStack = new Stack<WeakReference<Activity>>();
    // Activity对象引用变量，使用WeakReference，避免对GC产生影响
    private WeakReference<Activity> weakActivityReference;

    public synchronized static ActivityUtils getInstance() {
        if (null == instance) {
            instance = new ActivityUtils();
        }
        return instance;
    }

    public void addActivity(Activity activity) {
        if (activityStack == null)
            activityStack = new Stack<WeakReference<Activity>>();
        weakActivityReference = new WeakReference<Activity>(activity);
        activity = null;
        // activity弱引用对象加入堆栈
        if (!activityStack.contains(weakActivityReference))
            activityStack.push(weakActivityReference);
    }

    public Activity getCurrentActivity() {
        // 获取堆栈中的栈顶activity
        if (activityStack != null && !activityStack.isEmpty()) {
            return activityStack.peek().get();
        }
        return null;
    }

    public void exit() {
        try {
            ArrayList<Activity> activitiesOpened = getAllOpenedActivities();
            // 结束所有存活的activity
            // Finish all opened activities
            for (Activity activity : activitiesOpened) {
                finishActivity(activity);
            }
            // 释放对象
            activitiesOpened = null;
            // Finish the initial activity, pressing Back for good measure
            // finishActivity(getCurrentActivity(true, false));

            activityStack.clear();
            // 清空堆栈信息
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        }
    }

    private ArrayList<Activity> getAllOpenedActivities() {
        // 构造一个 List 用于返回 activity数组
        ArrayList<Activity> activities = new ArrayList<Activity>();
        // 遍历activityStack堆栈中的所有activity 加如到List中
        Iterator<WeakReference<Activity>> activityStackIterator = activityStack.iterator();
        // 判断是否可以继续遍历
        while (activityStackIterator.hasNext()) {
            // 获取当前activity,堆栈指针指向下个activity对象
            Activity activity = activityStackIterator.next().get();
            // 判断activity对象非空，才加入，可能由于gc导致对象已经被回收，导致null异常
            if (activity != null)
                activities.add(activity);
        }
        // 返回所有的当前存活activity
        return activities;
    }

    private void removeActivityFromStack(Activity activity) {
        // 遍历整个堆栈
        Iterator<WeakReference<Activity>> activityStackIterator = activityStack.iterator();

        while (activityStackIterator.hasNext()) {
            // 获取当前位置的activity
            Activity activityFromWeakReference = activityStackIterator.next().get();
            // 如果发现当前堆栈中存在 null对象，则移除之
            if (activityFromWeakReference == null) {
                activityStackIterator.remove();
            }
            // 找对了对应的activity,则移除之
            if (activity != null && activityFromWeakReference != null && activityFromWeakReference.equals(activity)) {
                activityStackIterator.remove();
            }
        }
    }

    public void FinishActivity(String activityName) {
        try {
            // 获取所有存活的activity
            ArrayList<Activity> activitiesOpened = getAllOpenedActivities();

            // 遍历所有存活的activity,如果存在指定的activity,则结束
            for (Activity activity : activitiesOpened) {
                if (activity.getLocalClassName().indexOf(activityName) >= 0) {
                    removeActivityFromStack(activity);
                    finishActivity(activity);
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }

    }

    public void FinishActivityExcept(String activityName) {
        try {
            // 获取所有存活的activity
            ArrayList<Activity> activitiesOpened = getAllOpenedActivities();

            // 遍历所有存活的activity,如果不存在指定的activity,则结束
            for (Activity activity : activitiesOpened) {
                if (activity.getLocalClassName().indexOf(activityName) < 0) {
                    removeActivityFromStack(activity);
                    finishActivity(activity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }

    }

    private void finishActivity(Activity activity) {
        if (activity != null) {
            try {
                activity.finish();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }
}
